using System.Collections.Generic;
using UnityEngine;

public class BuildingGenerator : MonoBehaviour
{
    public List<GameObject> buildingPrefabs; // 不同类型的建筑物预制件列表
    public float minDistanceBetweenBuildings = 5f; // 建筑物之间的最小距离
    public float buildingHeightRange = 3f; // 建筑物高度的随机范围
    public float spawnDistanceAhead = 50f; // 在玩家前方多远处开始生成建筑物
    public float buildingDespawnDistance = 5f; // 在玩家后方多远处移除建筑物
    
    private List<GameObject> activeBuildings = new List<GameObject>();
    private Transform playerTransform;
    private float lastSpawnPosition = 0f;
    private float trackWidth = 6f; // 跑道宽度，用于计算建筑物的生成位置
    
    void Start()
    {
        // 找到玩家对象
        playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
        
        // 如果没有找到玩家，使用默认位置
        if (playerTransform == null)
        {
            playerTransform = new GameObject("PlayerReference").transform;
        }
        
        // 初始生成一些建筑物
        for (int i = 0; i < 10; i++)
        {
            SpawnBuildingAtPosition(Random.Range(-trackWidth * 1.5f, trackWidth * 1.5f), lastSpawnPosition);
            lastSpawnPosition += Random.Range(minDistanceBetweenBuildings, minDistanceBetweenBuildings * 2);
        }
    }
    
    void Update()
    {
        // 当玩家移动时，在前方生成新的建筑物
        float spawnThreshold = playerTransform.position.z + spawnDistanceAhead;
        
        while (lastSpawnPosition < spawnThreshold)
        {
            // 随机决定在左侧还是右侧生成建筑物
            float xPosition = Random.value > 0.5f ? 
                Random.Range(-trackWidth * 3f, -trackWidth * 1.5f) : 
                Random.Range(trackWidth * 1.5f, trackWidth * 3f);
            
            SpawnBuildingAtPosition(xPosition, lastSpawnPosition);
            lastSpawnPosition += Random.Range(minDistanceBetweenBuildings, minDistanceBetweenBuildings * 2);
        }
        
        // 移除玩家后方超出距离的建筑物
        DespawnOldBuildings();
    }
    
    void SpawnBuildingAtPosition(float xPosition, float zPosition)
    {
        if (buildingPrefabs.Count == 0)
        {
            Debug.LogError("No building prefabs assigned!");
            return;
        }
        
        // 随机选择一个建筑物预制件
        int prefabIndex = Random.Range(0, buildingPrefabs.Count);
        GameObject prefab = buildingPrefabs[prefabIndex];
        
        // 固定X位置：左侧-8，右侧8
        float fixedXPosition = xPosition < 0 ? -8f : 8f;
        
        // 创建建筑物，设置Y位置为0.2（距离地面0.2）
        Vector3 spawnPosition = new Vector3(fixedXPosition, 0.2f, zPosition);
        
        // 根据位置设置旋转角度：左侧90度，右侧-90度
        Quaternion rotation;
        if (fixedXPosition < 0) // 左侧
        {
            rotation = Quaternion.Euler(0, 90, 0);
        }
        else // 右侧
        {
            rotation = Quaternion.Euler(0, -90, 0);
        }
        
        GameObject building = Instantiate(prefab, spawnPosition, rotation);
        
        // 随机调整建筑物的高度，增加变化性
        Vector3 scale = building.transform.localScale;
        scale.y *= 1 + Random.Range(0, buildingHeightRange);
        building.transform.localScale = scale;
        
        // 保持Y位置固定为0.2
        building.transform.position = new Vector3(fixedXPosition, 0.2f, zPosition);
        
        // 添加到活动建筑物列表
        activeBuildings.Add(building);
    }
    
    void DespawnOldBuildings()
    {
        // 移除超出玩家后面一定距离的建筑物
        float despawnThreshold = playerTransform.position.z - buildingDespawnDistance;
        
        for (int i = activeBuildings.Count - 1; i >= 0; i--)
        {
            if (activeBuildings[i].transform.position.z < despawnThreshold)
            {
                Destroy(activeBuildings[i]);
                activeBuildings.RemoveAt(i);
            }
        }
    }
}